package com.glowdayz.glowmee;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.glowdayz.model.PouchCategoryCMD;
import com.glowdayz.model.UserInfo;

public class ListPick extends Fragment implements OnItemClickListener {
	
	FrameLayout flContainer;
    DrawerLayout dlDrawer, dlDrawerIndex;
    View drawerView;
	
	ListView list_slidermenu = null;
	ArrayList<PouchCategoryCMD> list = null;
	LinearLayout llHeader = null;
	DataAdapter adapter = null;
	
	int paramFilter = 0, paramOrder = 0, paramGender = 0, paramAge = 0, paramSkin = 0;
	String paramPouchCategory = null;
	String paramType = null;
	
	ImageView addPouchBt = null;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        View nowView = inflater.inflate(R.layout.activity_list_pick, container, false);
		
		TextView textTitle = (TextView) nowView.findViewById(R.id.textTitle);
		textTitle.setText("글로우픽");
		
		flContainer = (FrameLayout) nowView.findViewById(R.id.fl_activity_main_container);
		dlDrawer = (DrawerLayout) nowView.findViewById(R.id.drawer_layout);
		drawerView = nowView.findViewById(R.id.drawer);
		
		dlDrawerIndex = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
		dlDrawerIndex.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		
		list_slidermenu = (ListView) nowView.findViewById(R.id.list_slidermenu);
		LayoutInflater inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llHeader = (LinearLayout) inflater2.inflate(R.layout.inc_pouch_side_header, null);
		
		if (UserInfo.getInstance().getUSER_ID() > 0) {
			addPouchBt = (ImageView) nowView.findViewById(R.id.addPouchBt);
			addPouchBt.setVisibility(View.VISIBLE);
			addPouchBt.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                switch (event.getAction()) {
	                    case MotionEvent.ACTION_DOWN: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
	                        view.invalidate();
	                        break;
	                    }
	                    case MotionEvent.ACTION_UP:
	                    case MotionEvent.ACTION_CANCEL: {
	                        ImageView view = (ImageView) v;
	                        view.getDrawable().clearColorFilter();
	                        view.invalidate();
	                        break;
	                    }
	                }
	                return false;
	            }
	        });
			addPouchBt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(), AddPouch.class);
					startActivityForResult(intent, 11);
				}
			});
		}
		
		ImageView okBt = (ImageView) nowView.findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.pick_search);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		
		okBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), PouchFilter.class);
				intent.putExtra("PARAM_category", paramPouchCategory);
				intent.putExtra("PARAM_order", paramOrder);
				intent.putExtra("PARAM_gender", paramGender);
				intent.putExtra("PARAM_age", paramAge);
				intent.putExtra("PARAM_skin", paramSkin);
				
				startActivityForResult(intent, 1);
			}
		});
		
		ImageView backBt = (ImageView) nowView.findViewById(R.id.backBt);
		backBt.setImageResource(R.drawable.pick_menu);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		
		backBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.openDrawer(drawerView);
			}
		});
		
		LinearLayout pickType1 = (LinearLayout) llHeader.findViewById(R.id.pickType1);
		pickType1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.closeDrawers();
				paramPouchCategory = null;
				fragmentReplace("전체픽");
			}
		});
		
		LinearLayout pickType2 = (LinearLayout) llHeader.findViewById(R.id.pickType2);
		pickType2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.closeDrawers();
				paramPouchCategory = "추천픽";
				fragmentReplace("추천픽");
			}
		});
		
		LinearLayout pickType3 = (LinearLayout) llHeader.findViewById(R.id.pickType3);
		pickType3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.closeDrawers();
				paramPouchCategory = "에디터픽";
				fragmentReplace("에디터픽");
			}
		});
		
		list_slidermenu.addHeaderView(llHeader);
		
		list = new ArrayList<PouchCategoryCMD>();
		adapter = new DataAdapter(getActivity(), list);
		list_slidermenu.setAdapter(adapter);
		list_slidermenu.setOnItemClickListener(this);
		
		adapter.add(new PouchCategoryCMD(1, "CATEGORY", R.drawable.pick_slide1));
		adapter.add(new PouchCategoryCMD(2, "이거샀어", R.drawable.pick_slide2));
		adapter.add(new PouchCategoryCMD(3, "이거어때", R.drawable.pick_slide3));
		adapter.add(new PouchCategoryCMD(4, "이거추천", R.drawable.pick_slide4));
		adapter.add(new PouchCategoryCMD(5, "사고싶어", R.drawable.pick_slide5));
		adapter.add(new PouchCategoryCMD(6, "아무거나", R.drawable.pick_slide6));
		
		fragmentReplace(paramType);
		
		return nowView;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 1) {
				paramFilter = data.getIntExtra("PARAM_filter", 0);
				paramOrder = data.getIntExtra("PARAM_order", 0);
				paramGender = data.getIntExtra("PARAM_gender", 0);
				paramAge = data.getIntExtra("PARAM_age", 0);
				paramSkin = data.getIntExtra("PARAM_skin", 0);
				paramPouchCategory = data.getStringExtra("PARAM_category");
				paramType = data.getStringExtra("PARAM_type");
				fragmentReplace(paramType);
			} else if (requestCode == 11) {
				fragmentReplace(paramType);
			}
			
		}
	}
	
	public class DataAdapter extends ArrayAdapter<PouchCategoryCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<PouchCategoryCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_pick_slide_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			PouchCategoryCMD item = getItem(position);
			
			/** "list_item.xml"내의 컨트롤들을 추출하여 데이터 출력. */

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				// 이미지를 표시하기 위한 이미지뷰 컨트롤
				ImageView menuImg = (ImageView) view.findViewById(R.id.menuImg);
				ImageView allowImg = (ImageView) view.findViewById(R.id.allowImg);
				TextView categoryTitle = (TextView) view.findViewById(R.id.categoryTitle);
				
				// 구조체 안에 지정된 이미지 리소스값을 사용하여 이미지를
				menuImg.setImageResource(item.getResId());
				categoryTitle.setText(item.getName());
				if (item.getName().equals("CATEGORY")) {
					categoryTitle.setTextColor(Color.parseColor("#e63646"));
					allowImg.setVisibility(View.INVISIBLE);
					list_slidermenu.setSelector(android.R.color.transparent);
				} else {
					view.setOnTouchListener(new OnTouchListener() {
						@Override
						public boolean onTouch(View v, MotionEvent arg1) {
							v.setBackgroundResource(android.R.drawable.list_selector_background);
							return false;
						}
					});
				}
			}
			return view;
		}
	}
	
	public void fragmentReplace(String reqNewFragmentIndex) {
		Bundle bundle = new Bundle();
		
		if (reqNewFragmentIndex != null) {
			if (reqNewFragmentIndex.equals("추천픽") || reqNewFragmentIndex.equals("에디터픽") || reqNewFragmentIndex.equals("전체픽") || reqNewFragmentIndex.equals("이거샀어")
				 || reqNewFragmentIndex.equals("이거어때") || reqNewFragmentIndex.equals("이거추천") || reqNewFragmentIndex.equals("사고싶어") || reqNewFragmentIndex.equals("아무거나")) {
				paramOrder = 0;
				paramGender = 0;
				paramAge = 0;
				paramSkin = 0;
				Index.isLiskPick = false;
				if (reqNewFragmentIndex.equals("전체픽")) {
					reqNewFragmentIndex = null;
				}
			} else {
				bundle.putInt("PARAM_filter", paramFilter);
				bundle.putInt("PARAM_order", paramOrder);
				bundle.putInt("PARAM_gender", paramGender);
				bundle.putInt("PARAM_age", paramAge);
				bundle.putInt("PARAM_skin", paramSkin);
				bundle.putString("PARAM_category", paramPouchCategory);
			}
		} else {
			bundle.putInt("PARAM_filter", paramFilter);
			bundle.putInt("PARAM_order", paramOrder);
			bundle.putInt("PARAM_gender", paramGender);
			bundle.putInt("PARAM_age", paramAge);
			bundle.putInt("PARAM_skin", paramSkin);
			bundle.putString("PARAM_category", paramPouchCategory);
		}
		
		bundle.putString("PARAM_pouchCategory", reqNewFragmentIndex);
		
        Fragment newFragment = new PouchFm();
        newFragment.setArguments(bundle);
        final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.ll_fragment, newFragment);
        transaction.commit();
    }

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		switch (arg2) {
		case 1:
			dlDrawer.closeDrawers();
			break;
		case 2:
			dlDrawer.closeDrawers();
			paramPouchCategory = "이거샀어";
			fragmentReplace("이거샀어");
			break;
		case 3:
			dlDrawer.closeDrawers();
			paramPouchCategory = "이거어때";
			fragmentReplace("이거어때");
			break;
		case 4:
			dlDrawer.closeDrawers();
			paramPouchCategory = "이거추천";
			fragmentReplace("이거추천");
			break;
		case 5:
			dlDrawer.closeDrawers();
			paramPouchCategory = "사고싶어";
			fragmentReplace("사고싶어");
			break;
		case 6:
			dlDrawer.closeDrawers();
			paramPouchCategory = "아무거나";
			fragmentReplace("아무거나");
			break;
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		list_slidermenu.removeHeaderView(llHeader);
	}

}
